package com.yixun.qfbao.hander;

import com.yixun.qfbao.service.PartnerInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yixun.qfbao.api.service.OrganizationService;
import com.yixun.qfbao.apidto.GetCompanyByUserIdReqDto;
import com.yixun.qfbao.apidto.GetCompanyByUserIdResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.vo.GetCompanyByUserIdReqVo;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

import java.util.Objects;

/**
 * 根据用户id获取公司信息
 * @author xiaojin.li
 *
 */
@Service("getCompanyByUserIdHander")
public class GetCompanyByUserIdHander extends CommonAbstractHander {
	private static Logger logger= LoggerFactory.getLogger(GetCompanyByUserIdHander.class);
	
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private LoginUtils loginUtils;
	@Autowired
	private PartnerInfoService partnerInfoService;

	@Override
	public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
		GetCompanyByUserIdReqVo req = (GetCompanyByUserIdReqVo)reqDto;
		GetCompanyByUserIdReqDto reqDto1 = req.getParams();
		BaseResponseDTO<GetCompanyByUserIdResDto> res = new BaseResponseDTO<>();
		GetCompanyByUserIdResDto resDto = new GetCompanyByUserIdResDto();
		try {
			PartnerInfo partner = loginUtils.getUser(reqDto1.getUserId());
			if(Objects.isNull(partner) && StringUtils.isNotBlank(reqDto1.getUserId())){
				partner = partnerInfoService.selectById(Long.valueOf(reqDto1.getUserId()));
			}
			reqDto1.setHigherId(partner.getHigherid());
			resDto = organizationService.getCompanyByUserId(reqDto1);
		}catch(TServerException e){
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg(e.getErrorMsg());
		} catch (Exception e) {
			logger.error("GetCompanyByUserIdHander error: {}", e);
			resDto.setResult(ResultEnum.FAIL.getNo());
			resDto.setResultMsg("系统异常");
		}
		res.setResData(resDto);
		res.setResult(resDto.getResult());
		return res;
	}
	
}
